//
//  ReadCollectionViewController.m
//  Lesson_Read
//
//  Created by 李洪鹏 on 15-4-25.
//  Copyright (c) 2015年 ___蓝鸥科技公司___. All rights reserved.
//

#import "ReadCollectionViewController.h"
#import "ReadCollectionViewCell.h"
#import "AFNetworking.h"
#import "URLs.h"
#import "UIImageView+WebCache.h"
#import "ReadList.h"
#import "ReadListView.h"
#import "ReadDetailsTableViewController.h"
#import "MJRefresh.h"
#import "RESideMenu.h"




#define BASE_URL_2 @"http://api2.pianke.me/read/columns"


@interface ReadCollectionViewController ()

#pragma mark - 声明私有属性

@property (nonatomic, retain)NSMutableArray *allDataArray;
@property (nonatomic, retain)ReadListView *readListView;

#pragma mark - 设置私有方法
- (void)loadData;

@end

@implementation ReadCollectionViewController

static NSString * const reuseIdentifier = @"Cell";  //全局变量


- (void)loadView
{
    // 创建系统自带的布局对象
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout new] autorelease];
    
    flowLayout.itemSize = CGSizeMake(100 / 375.0 *  kScreenWidth, 120 / 667.0 *kScreenHeight);
    flowLayout.minimumLineSpacing = 5 / 667.0 *kScreenHeight; // 设置最小行间距
    flowLayout.minimumInteritemSpacing = 5 / 375.0 *kScreenWidth; // 设置最小列间距
    flowLayout.headerReferenceSize = CGSizeMake(0, 20 / 667.0 *kScreenHeight); // 头区大小
    flowLayout.footerReferenceSize = CGSizeMake(0, 20 / 667.0 *kScreenHeight); // 尾区大小
    
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 20 / 667.0 *kScreenWidth, 0, 20 / 667.0 *kScreenWidth);
    
    self.navigationItem.title = @"阅读";
    
    
    // 设置根视图
    
    self.readListView = [[[ReadListView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout] autorelease];
    self.collectionView = _readListView;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    
    self.navigationItem.title = @"阅读";
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    // 设置左navigationbarButton
  self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)] autorelease];
    
    // 设置右navigationbarButton
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"RightMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(presentRightMenuViewController:)] autorelease];
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //注册
    [self.collectionView registerNib:[UINib nibWithNibName:@"ReadCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    self.allDataArray = [NSMutableArray array];

    
    //加载数据
    [self loadData];
    
    [self.collectionView addLegendHeaderWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        [self.collectionView.header beginRefreshing];
        [self.collectionView.header endRefreshing];
    }];
    

}


//加载数据
- (void)loadData
{
    
    
    __block typeof(self)weakSelf = self;
    
    NSURL *url = [NSURL URLWithString:@"http://api2.pianke.me/read/columns"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 准备AFHTTPRequestOperation
    AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        NSData *data = operation.responseData;
        
           NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        
        for (NSDictionary *item in dict[@"data"][@"list"]) {

            ReadList *read = [ReadList new];
            [read setValuesForKeysWithDictionary:item];
            [weakSelf.allDataArray addObject:read];
            

            }
        [self.collectionView reloadData];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.collectionView reloadData];
        });

 

        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@", [error localizedDescription]);
    }];
    // 开始获取数据
    [operation start];
    
    
  
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return _allDataArray.count;
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ReadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    ReadList *r = _allDataArray[indexPath.row];
    cell.Readtitle.text = r.name;
    cell.ReadEnglishtitle.text = r.enname;
    
    
    // 使用SDWebImage下载网络图片
//    NSLog(@"!!!!!!!!!!!!%@", dict[@"coverimg"]);
    [cell.ReadView sd_setImageWithURL:[NSURL URLWithString:r.coverimg]];
    
    
    
    return cell;
}



//推出详情
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ReadList *read = _allDataArray[indexPath.row];
    
    
    ReadDetailsTableViewController *readTVC = [[ReadDetailsTableViewController new] autorelease];

    readTVC.readtypeId = read.type;
    
    [self.navigationController pushViewController:readTVC  animated:YES];
    
}







#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/



-(void)dealloc
{
    [_allDataArray release];
    [_readListView release];
    
    [super dealloc];
    
}






@end
